
/**
** \file       funcdec.c
**
** \brief      this function parse the fundec rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse, De Olivera
**             Guillaume and Nguyen Viet Dung
**
** \version    0.8
**
** \date       26 Novembre 2010
**
*/

#include "rules.h"

static int              next_token(void)
{
  if (g_data->lexer == NULL)
    return (1);

  g_data->lexer = g_data->lexer->next;

  return (0);
}

static s_funcdec        *rule_funcdec1(s_funcdec        *funcdec)
{
  if (next_token())
    return (NULL);
  if (!strcmp(g_data->lexer->token->id, ")"))
  {
    if (next_token())
      return (NULL);
    while (!strcmp(g_data->lexer->token->id, "\n"))
    {
      if (next_token())
        return (NULL);
    }
    if (rule_shell_command(funcdec->sh_cmd))
      return (NULL);
    return (funcdec);
  }
  return (NULL);
}

static s_funcdec        *my_free1(s_funcdec             *funcdec,
                                  int                   n)
{
  if (n == 1)
  {
    free(funcdec->word);
    funcdec->word = NULL;

    free(funcdec->function);
    funcdec->function = NULL;

    return (NULL);
  }
  if (n == 2)
  {
    free(funcdec->sh_cmd);
    funcdec->sh_cmd = NULL;

    free(funcdec->word);
    funcdec->word = NULL;

    free(funcdec->function);
    funcdec->function = NULL;

    free(funcdec->sh_cmd);
    funcdec->sh_cmd = NULL;

    return (NULL);
  }

  return (NULL);
}

static s_funcdec        *my_malloc(s_funcdec            *funcdec)
{
  funcdec->sh_cmd = calloc(1, sizeof (s_sh_cmd));

  return (funcdec);
}

static s_funcdec        *my_free2(s_funcdec             *funcdec)
{
  free(funcdec->word);
  funcdec->word = NULL;

  free(funcdec->function);
  funcdec->function = NULL;

  return (NULL);
}

s_funcdec               *rule_funcdec(s_funcdec         *funcdec)
{
  if (g_data->lexer == NULL)
    return (NULL);

  if (!strcmp(g_data->lexer->token->id, "function"))
  {
    funcdec->function = malloc(sizeof (char) * strlen("function"));
    funcdec->function = strcpy(funcdec->function, "function");
    g_data->lexer = g_data->lexer->next;
  }

  if (g_data->lexer->token->type != TOKEN_WORD)
    return (NULL);

  if (g_data->lexer != NULL && g_data->lexer->next != NULL
      && strcmp(g_data->lexer->next->token->id, "(") != 0)
    return (NULL);

  funcdec->word = calloc(1, sizeof (char) * strlen(g_data->lexer->token->id));
  funcdec->word = strcpy(funcdec->word, g_data->lexer->token->id);

  if (next_token())
    return (my_free1(funcdec, 1));

  if (!strcmp(g_data->lexer->token->id, "("))
  {
    funcdec = my_malloc(funcdec);

    if (rule_funcdec1(funcdec))
      return (my_free1(funcdec, 2));

    return (funcdec);
  }

  return (my_free2(funcdec));
}
